import React from "react";
import Admin from "../../layout/Admin";

import {Table, Image, Popover, Modal, Form, Button, Input, InputNumber, Upload, DatePicker, Popconfirm,} from "antd";
import PaginationFooter from "../../component/PaginationFooter/PaginationFooter";
import moment from "moment";

import Info from "../../service/info";
import {log, formTailLayout, formLayout, getBase64} from '../quotation/quotation'
import MallModel from "../../model/mall";
import {CloseCircleOutlined, UploadOutlined, MinusCircleOutlined, PlusOutlined} from "@ant-design/icons";
import QuotationModel from "../../model/quotation";

class Mall extends React.Component {
    constructor(props) {
        super(props)
        this.model = new MallModel()
        this.quotationModel = new QuotationModel()
        this.columns = [
            // Check: 2
            // Id: 178
            {
                dataIndex: 'Id',
                title: 'Id',
            },
            // Hid: 178
            {
                dataIndex: 'Hid',
                title: '行情ID',
            },
            // Pinpai: "雨林"
            {
                dataIndex: 'Pinpai',
                title: '品牌',
            },
            // Name: "雨林2021年紫电清霜"
            {
                dataIndex: 'Name',
                title: '品名',
            },
            // Price: 4750000
            {
                dataIndex: 'Price',
                title: '价格',
            },
            // Gongyi: "生茶"
            {
                dataIndex: 'Gongyi',
                title: '工艺'
            },
            // Style: "饼茶"
            {
                dataIndex: 'Style',
                title: '类型'
            },
            // Guige: "357克/片5片/提2提/件"
            {
                dataIndex: 'Guige',
                title: '规格',
                render: (text, record) => {
                    return <div>
                        <span style={{marginRight: '8px',}}>{text}</span>
                        <Popover
                            trigger='click'
                            title='规格详情'
                            content={this.state.items.map((item, index) => {
                                return <div key={index} style={{marginBottom: '8px',}}>
                                    <p>
                                        {item.Guige}
                                    </p>
                                    <span>价格:{item.Price} 售出:{item.Sellnum} 库存:{item.Totalnum} 运费:{item.Yunfei}</span>

                                </div>
                            })}
                        >
                            <a
                                onClick={() => this.getDetail(record)}
                            >查看</a>
                        </Popover>

                    </div>
                }
            },
            // Pici: ""
            {
                dataIndex: 'Pici',
                title: '批次'
            },

            // Xulie: ""
            {
                dataIndex: 'Xulie',
                title: '序列'
            },
            {
                dataIndex: 'Productiondate',
                title: '生产日期',
                render: (time) => moment(new Date(time * 1000)).format('YYYY-MM-DD')
            },
            // Expiredate: 0
            {
                dataIndex: 'Expiredate',
                title: '过期日期',
                render: (time) => time > time && moment(new Date(time * 1000)).format('YYYY-MM-DD')
            },
            // Detailimgs: null
            {
                dataIndex: 'Imgs',
                title: '轮播图',
                render: (imgs) => {
                    return <Popover
                        title='轮播图'
                        trigger='click'
                        content={<div>
                            {imgs && imgs.map((img, index) => <img src={img} key={index} alt='' style={{width: 200,}}/>)}
                        </div>}
                    >
                        <a>查看</a>
                    </Popover>
                }
            },
            {
                dataIndex: 'Detailimgs',
                title: '详情图',
                render: (imgs) => {
                    // log(imgs)
                    if (imgs && imgs.length > 0) {
                        return <Popover
                            title='轮播图'
                            trigger='click'
                            content={<div>
                                {imgs && imgs.map((img, index) => <img src={img} key={index} alt='' style={{width: 200,}}/>)}
                            </div>}
                        >
                            <a>查看</a>
                        </Popover>
                    }
                }
            },

            {
                title: '操作',
                render: (recode) => {
                    return <div className='action-links'>
                        <a
                            onClick={() => this.callEdit(recode)}
                        >编辑</a>
                        <Popconfirm
                            title={'确认删除？'}
                            onConfirm={() => this.delete(recode)}
                            okText="确认"
                            cancelText="取消"
                        >
                            <a>删除</a>
                        </Popconfirm>

                    </div>
                }
            },
        ]
        this.state = {
            list: [],
            p: 0,
            modal: {
                add: false,
                preview: false,
                quotations: false,
            },
            previewImage: null,
            previewTitle: '',
            edit: false,
            add: false,
            editValue: null,
            imgs: [],
            detailImgs: [],
            quotations: [],
            items: [],
        }
    }

    componentDidMount() {
        this.all()
    }

    all = () => {
        const params = {
            PinPai: [], //     string//品牌
            P: this.state.p, //          int //页数
            Gongyi: [], // 工艺
            Year: [], //       int //0不过滤
            Hot: 0, //        int //0不过滤，1从高到低，2从低到高
            PriceStart: 0, // float64//价格过滤
            PriceEnd: 0, //  float64
        }
        this.model
            .all(params)
            .then(res => {
                const code = res.data.code
                if (code === 0) {
                    const data = res.data.data
                    log('all,', data)
                    this.setState({
                        list: data,
                    })
                }
            })
    }

    getDetail = (record) => {
        this.model.get({Id: record.Id})
            .then((res) => {
                const data = res.data
                if (data.code === 0) {
                    this.setState({
                        items: data.data.it,
                    })
                }
            })
    }

    check = (record) => {
        const checked = record.Shenhe
        if (checked !== 2) {
            record.Shenhe = 2
        } else {
            record.Shenhe = 1
        }
        this.onAdd(record)
    }

    delete = (record) => {
        this.model
            .delete({
                Id: record.Id,
            })
            .then(res => {
                const code = res.data.code
                if (code === 0) {
                    Info.success('删除成功')
                    this.all()
                } else {
                    Info.error(res.data.error)
                }
            })
    }

    onAdd = (value) => {
        if (value.Productiondate) {
            value.Productiondate = parseInt(moment(value.Productiondate).format('X'))
        }
        if (value.Expiredate) {
            value.Expiredate = parseInt(moment(value.Expiredate).format('X'))
        }
        if (this.state.add) {
            if (this.state.editValue && this.state.editValue.Imgs) {
                value.imgs = [...this.state.editValue.Imgs, ...this.state.imgs,]
            } else {
                value.imgs = [...this.state.imgs,]
            }
            if (this.state.editValue && this.state.editValue.Detailimgs) {
                value.detailImgs = [...this.state.editValue.Detailimgs, ...this.state.detailImgs,]
            } else {
                value.detailImgs = [...this.state.detailImgs,]
            }
            if (this.state.editValue && this.state.editValue.Id) {
                value.Hid = this.state.editValue.Id
            }

        }
        if (this.state.edit) {
            value.imgs = [...this.state.imgs,]
            if (this.state.editValue.Imgs) {
                value.imgs = [...this.state.editValue.Imgs, ...this.state.imgs,]
            } else {
                value.imgs = [...this.state.imgs,]
            }
            if (this.state.editValue.Detailimgs) {
                value.detailImgs = [...this.state.editValue.Detailimgs, ...this.state.detailImgs,]
            } else {
                value.detailImgs = [...this.state.detailImgs,]
            }
            value.Id = this.state.editValue.Id
        }
        if (value.Id) {
            value.Item = value.Item.map(item => ({...item, Gid: value.Id}))
        }
        this.model
            .add(value)
            .then(res => {
                if (res.data.code === 0) {
                    Info.success('上传/编辑成功')
                    this.addForm && this.addForm.resetFields()
                    this.cancelModal('add')
                    this.setState({
                        imgs: [],
                        detailImgs: [],
                        edit: false,
                        add: false,
                        editValue: null,
                    })
                    this.all()
                } else {
                    Info.warning(res.data.err)
                }
            })
    }

    callAdd = (record) => {
        log(record)
        this.callModal('add')
        this.setState({
            editValue: record,
            add: true,
        })
        if (record.Expiredate) {
            record.Expiredate = moment(new Date(record.Expiredate * 1000))
        }
        if (record.Productiondate) {
            record.Productiondate = moment(new Date(record.Productiondate * 1000))
        }
        setTimeout(() => {
            this.addForm.setFieldsValue({
                ...record,
            })
        }, 0)
    }

    callEdit = (record) => {
        this.callModal('add')
        log(record)

        const formValue = {
            ...record
        }
        if (record.Expiredate) {
            formValue.Expiredate = moment(new Date(record.Expiredate * 1000))
        }
        if (record.Productiondate) {
            formValue.Productiondate = moment(new Date(record.Productiondate * 1000))
        }

        this.model
            .get({Id: record.Id})
            .then((res) => {
                const data = res.data
                if (data.code === 0) {
                    log(data)
                    formValue.Item = data.data.it
                    this.setState({
                        editValue: record,
                        edit: true,
                    })
                    setTimeout(() => {
                        this.addForm.setFieldsValue({
                            ...formValue,
                        })
                    }, 0)
                }
            })


    }

    onNameSearch = (value) => {
        if (value) {
            const params = {
                Keys: [value,],
                P: -1,
            }
            this.quotationModel
                .findByName(params)
                .then((res) => {
                    const code = res.data.code
                    if (code === 0) {
                        const data = res.data.data.d
                        log(data)
                        this.setState({
                            quotations: data,
                        }, () => this.callModal('quotations'))
                    } else {
                        Info.error(res.data.error)
                    }
                })
        } else {
            this.setState({
                add: true,
            }, () => this.callModal('add'))

        }
    }


    prevPage = () => {
        this.setState({
            p: this.state.p - 1,
        }, () => this.all())
    }

    nextPage = () => {
        this.setState({
            p: this.state.p + 1,
        }, () => this.all())
    }

    callModal(key) {
        this.setState({
            ...this.state,
            modal: {
                ...this.state.modal,
                [key]: true,
            }
        })
    }

    cancelModal(key) {
        this.setState({
            ...this.state,
            modal: {
                ...this.state.modal,
                [key]: false
            }
        })
    }

    onAddFormCancel = () => {
        this.cancelModal('add')
        this.addForm.resetFields()
        this.setState({
            edit: false,
            add: false,
            imgs: [],
            detailImgs: [],
            editValue: null
        })
    }

    deleteEditImage = (index, name) => {
        const imgs = this.state.editValue[name]
        imgs.splice(index, 1)
        this.setState({
            editValue: {
                ...this.state.editValue,
                [name]: imgs,
            }
        })
    }

    uploadInputProps = (name) => {

        const fileList = this.state[name]

        return {

            onRemove: file => {
                this.setState(state => {
                    const index = state[name].indexOf(file);
                    const newFileList = state[name].slice();
                    newFileList.splice(index, 1);
                    return {
                        [name]: newFileList,
                    }
                })
            },

            beforeUpload: () => false,

            onChange: ({fileList,}) => {
                this.setState({
                    [name]: fileList,
                })
            },

            onPreview: async (file) => {
                if (!file.url && !file.preview) {
                    file.preview = await getBase64(file.originFileObj);
                }

                this.setState({
                    previewImage: file.url || file.preview,
                    previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
                }, () => this.callModal('preview'));
            },

            fileList,
        }

    }

    renderItemFields = (fields, {add, remove,}, lineupKey) => {
        return (
            <>
                {fields.map(({ key, name, fieldKey, ...restField }, index) => (
                    <div key={key} style={{display: 'flex', marginLeft: '33.3333333%'}}>
                        <Form.Item
                            {...restField}
                            name={[name, 'Guige']}
                            fieldKey={[fieldKey, 'Guige']}
                            label='规格名称'
                        >
                            <Input placeholder="规格" style={{width: 100,}}/>
                        </Form.Item>
                        <Form.Item
                            {...restField}
                            name={[name, 'Price']}
                            fieldKey={[fieldKey, 'Price']}
                            label='价格'
                        >
                            <InputNumber placeholder="价格" style={{width: 100,}}/>
                        </Form.Item>
                        <Form.Item
                            {...restField}
                            name={[name, 'Totalnum']}
                            fieldKey={[fieldKey, 'Totalnum']}
                            label='库存'
                        >
                            <InputNumber placeholder="库存" style={{width: 100,}}/>
                        </Form.Item>
                        <Form.Item
                            {...restField}
                            name={[name, 'Sellnum']}
                            fieldKey={[fieldKey, 'Sellnum']}
                            label='卖出数'
                        >
                            <InputNumber placeholder="卖出数" style={{width: 100,}}/>
                        </Form.Item>
                        <MinusCircleOutlined onClick={() => remove(name)} style={{margin: '10px'}} />
                    </div>
                ))}
                <Form.Item {...formTailLayout}>
                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                        添加规格
                    </Button>
                </Form.Item>
            </>
        )
    }


    render() {
        return (
            <>
                <Modal
                    visible={this.state.modal.preview}
                    title={this.state.previewTitle}
                    footer={null}
                    onCancel={() => this.cancelModal('preview')}
                >
                    <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
                </Modal>

                <Modal
                    visible={this.state.modal.quotations}
                    title={'选择行情以添加商品'}
                    footer={null}
                    onCancel={() => this.cancelModal('quotations')}
                >
                    {this.state.quotations.map((q, index) => <div key={index}>
                        <a onClick={() => this.callAdd(q)}
                        >{q.Name}</a>
                    </div>)}
                </Modal>

                <Modal
                    visible={this.state.modal.add}
                    onCancel={this.onAddFormCancel}
                    footer={null}
                    title={'茶叶表单'}
                    width='80%'
                >
                    <Form
                        {...formLayout}
                        name='add'
                        ref={el => this.addForm = el}
                        onFinish={this.onAdd}
                    >
                        {/*Id              int64 //修改的时候传，不修改传0*/}
                        {/*Pinpai          string //品牌*/}
                        <Form.Item
                            label="品牌"
                            name="Pinpai"
                        >
                            <Input placeholder='请输入品牌'/>
                        </Form.Item>
                        {/*Name            string //名字*/}
                        <Form.Item
                            label="商品名称"
                            name="Name"
                        >
                            <Input placeholder='请输入品名'/>
                        </Form.Item>

                        <Form.List
                            name="Item"
                        >
                            {(fields, { add, remove, },) => this.renderItemFields(fields, { add, remove, }, 'Item')}
                        </Form.List>

                        <Form.Item
                            label='生产日期'
                            name='Productiondate'
                        >
                            <DatePicker />
                        </Form.Item>

                        <Form.Item
                            label='过期日期'
                            name='Expiredate'
                        >
                            <DatePicker />
                        </Form.Item>

                        {/*Price           int64  //价格*/}
                        <Form.Item
                            label="价格"
                            name="Price"
                        >
                            <InputNumber placeholder='请输入价格'/>
                        </Form.Item>
                        {/*Guige           string //规格*/}
                        <Form.Item
                            label="规格"
                            name="Guige"
                        >
                            <Input placeholder='请输入规格'/>
                        </Form.Item>
                        {/*Gongyi          string //工艺*/}
                        <Form.Item
                            label="工艺"
                            name="Gongyi"
                        >
                            <Input placeholder='请输入工艺'/>
                        </Form.Item>
                        {/*Style           string //类型*/}
                        <Form.Item
                            label="类型"
                            name="Style"
                        >
                            <Input placeholder='请输入类型'/>
                        </Form.Item>

                        {/*Pici            string //批次*/}
                        <Form.Item
                            label="批次"
                            name="Pici"
                        >
                            <Input placeholder='请输入批次'/>
                        </Form.Item>
                        <Form.Item
                            label="序列"
                            name="Xulie"
                        >
                            <Input placeholder='请输入序列'/>
                        </Form.Item>

                        {/*Imgs            string //图片*/}
                        {(this.state.edit || this.state.add) && <Form.Item
                            label='轮播图图片'
                        >
                            {this.state.editValue && this.state.editValue.Imgs.map((src, index) => {
                                return <div
                                    key={index}
                                    style={{position: 'relative', display: 'inline-block'}}
                                >
                                    <img src={src} alt='' style={{width: 200}}/>
                                    <CloseCircleOutlined
                                        style={{position: 'absolute', top: 0, right: 0,}}
                                        onClick={() => {
                                            this.deleteEditImage(index, 'Imgs')
                                        }}
                                    />
                                </div>
                            })}
                        </Form.Item>}
                        <Form.Item
                            label="上传轮播图图片"
                        >
                            <Upload
                                listType="picture-card"
                                fileList={this.state.imgs}
                                {...this.uploadInputProps('imgs')}
                                multiple={true}
                            >
                                <Button icon={<UploadOutlined />}>上传轮播图</Button>
                            </Upload>
                        </Form.Item>
                        {/*Detailimgs      string//详情图片*/}
                        {(this.state.edit || this.state.add) && this.state.editValue && this.state.editValue.Detailimgs && <Form.Item
                            label='详情图片'
                        >
                            {this.state.editValue.Detailimgs.map((src, index) => {
                                return <div
                                    key={index}
                                    style={{position: 'relative', display: 'inline-block'}}
                                >
                                    <img src={src} alt='' style={{width: 200}}/>
                                    <CloseCircleOutlined
                                        style={{position: 'absolute', top: 0, right: 0,}}
                                        onClick={() => {
                                            this.deleteEditImage(index, 'Detailimgs')
                                        }}
                                    />
                                </div>
                            })}
                        </Form.Item>}
                        <Form.Item
                            label="上传详情图片"
                        >
                            <Upload
                                listType="picture-card"
                                fileList={this.state.imgs}
                                {...this.uploadInputProps('detailImgs')}
                                multiple={true}
                            >
                                <Button icon={<UploadOutlined />}>上传详情图片</Button>
                            </Upload>
                        </Form.Item>

                        <Form.Item {...formTailLayout}>

                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>

                        </Form.Item>

                    </Form>
                </Modal>
                <Admin>
                    <div className='list-container'>
                        <div style={{marginBottom: '8px'}}>
                            {/*<Button onClick={() => this.callModal('add')}>添加商品</Button>*/}

                            <Input.Search
                                placeholder="可输入品名按行情添加 空则直接添加"
                                allowClear
                                enterButton="添加商品"
                                size="large"
                                onSearch={this.onNameSearch}
                                style={{
                                    width: '500px',
                                    marginBottom: '8px',
                                    display: 'block'
                                }}
                            />
                        </div>
                        <Table
                            dataSource={this.state.list}
                            columns={this.columns}
                            pagination={false}
                            rowKey={(record, index) => index}
                            // scroll={{ x: 2500,}}
                        />
                        <PaginationFooter
                            pageIndex={this.state.p}
                            prevPage={this.prevPage}
                            nextPage={this.nextPage}
                        />
                    </div>
                </Admin>
            </>
        )
    }

}

export default Mall